#encoding=utf-8

import urllib.request
import urllib.parse
import time
import json
import random
import hashlib


def get_token():
    # 需要翻译的文本
    text = input("请输入需要翻译的词: ")
    #计算salt值,这里的time值是本机时间,需要加上请求翻译时间
    salt = str(int(time.time()*1000) + random.randint(0, 10))
    #计算sign值,通过md5机密生成,这里的"sr_3(QOHT)L2dx#uuGR@r"是"加盐"处理,用来防止黑客通过值来反推算出原始值,参考https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0013868328251266d86585fc9514536a638f06b41908d44000
    #hash.hexdigest()返回摘要,作为十六进制数据字符串值,hash.digest()返回摘要,作为二进制数据字符串值
    sign = hashlib.md5(("fanyideskweb" + text + salt + "sr_3(QOHT)L2dx#uuGR@r").encode("utf-8")).hexdigest()

    return text, salt, sign

def send_request():
    post_url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"

    headers = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            #"Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Length": "214",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Cookie": "OUTFOX_SEARCH_USER_ID=-1729206679@10.168.8.63; OUTFOX_SEARCH_USER_ID_NCOO=706918302.8300428; _ntes_nnid=eccc195bbd2a604587a4174b4baf39d1,1539955044648; fanyi-ad-id=52077; fanyi-ad-closed=1; JSESSIONID=aaaPOEb-L5bML-VPi8pCw; ___rl__test__cookies=1542160697195",
            "Host": "fanyi.youdao.com",
            "Origin": "http://fanyi.youdao.com",
            "Referer": "http://fanyi.youdao.com/",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest",
            }

    text, salt, sign = get_token()
    
    """
    在js文件中找到产生salt和sign的地方如下:
    define("newweb/common/service", ["./utils", "./md5", "./jquery-1.7"],
    function(e, t) {
        var n = e("./jquery-1.7");
            e("./utils");
            e("./md5");
            var r = function(e) {
            var t = "" + ((new Date).getTime() + parseInt(10 * Math.random(), 10));
            return {
                    salt: t,
                    sign: n.md5("fanyideskweb" + e + t + "sr_3(QOHT)L2dx#uuGR@r")
                    }
            };
    },
    ...
    )
    """
    #构建post请求表单数据
    form_data = {
            "i": text,
            "from": "AUTO",
            "to": "AUTO",
            "smartresult": "dict",
            "client": "fanyideskweb",
            "salt": salt,
            "sign": sign,
            "doctype": "json",
            "version": "2.1",
            "keyfrom": "fanyi.web",
            "action": "FY_BY_REALTIME",
            "typoResult": "false",
            }
    
    form_data = urllib.parse.urlencode(form_data).encode("utf-8")
    headers["Content-Length"] = len(form_data)

    request = urllib.request.Request(post_url, form_data, headers=headers)
    #设置超时时间
    response = urllib.request.urlopen(request, timeout=3)

    json_data = json.loads(response.read().decode("utf-8"))

    print(json_data['translateResult'][0][0]['tgt'])


if __name__ == "__main__":
    send_request()

